<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img {
            width: 100%;
        }

        .btn {
            position: fixed;
            width: 160px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            bottom: 10px;
            right: 5px;
            background: orangered;
            color: #fff;
            font-size: 20px;
            border-radius: 20px;
        }
    </style>
</head>

<body>
    <img src="" alt="">
    <div id="price"></div>
    <div id="name"></div>
    <div class="btn">加入购物车</div>

    <script>
        // 购物车里的一条数据，是一个对象
        var item1 = {
            id: 45498,
            imgsrc: "https://hotkidceo-1251330842.file.myqcloud.com/2022062414262400203.jpg",
            price: 472,
            num: 1,
            name: "旺仔俱乐部旺仔零食售货机系列整盒"
        };
        //数据写在页面上
        var oP = document.querySelector('#price');
        var oName = document.querySelector('#name');
        var oImg = document.querySelector('img');
        var oBtn = document.querySelector('.btn');
        oP.innerHTML = item1.price;
        oName.innerHTML = item1.name;
        oImg.src = item1.imgsrc;

        //给按钮绑定点击事件
        oBtn.onclick = function () {
            //添加购物车 ,需要用到缓存
            //1.先从购物车中获取缓存中的数据,对数据进行反序列化,如果没有数据，给空数组

            var oldArr = localStorage.getItem('cart') == null ? [] : JSON.parse(localStorage.getItem('cart'));
            //2.将添加购物车的数据追加到数组中
            oldArr.push(item1);

            //3.将最新的数据序列化，保存到缓存
            localStorage.setItem('cart', JSON.stringify(oldArr));
        }





    </script>
</body>

</html>